#define _CRT_SECURE_NO_WARNINGS
#include "Seqlist.h"


void SeqListInit(SeqList* ps)
{
	ps->a = (SLDateType*)malloc(sizeof(SLDateType) * 4);
	ps->capacity = 4;
	ps->size = 0;
}


void SeqListDestroy(SeqList* ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->capacity = 0;
	ps->size = 0;
}


void SeqListPrint(SeqList* ps)
{
	assert(ps);
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", ps->a[i]);
	}
	printf("\n");
}


static void CheckCapacity(SeqList* ps)
{
	if (ps->capacity == ps->size)
	{
		ps->a = (SLDateType*)realloc(ps->a, sizeof(SLDateType) * ps->capacity * 2);
		if (ps->a == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->capacity *= 2;
	}
	return;
}


void SeqListPushBack(SeqList* ps, SLDateType x)
{
	assert(ps);
	CheckCapacity(ps);

	/*ps->a[ps->size] = x;
	ps->size++;*/
	SeqListInsert(ps, ps->size, x);
}


void SeqListPushFront(SeqList* ps, SLDateType x)
{
	assert(ps);
	CheckCapacity(ps);

	/*int end = ps->size;
	for (end; end > 0; end--)
	{
		ps->a[end] = ps->a[end - 1];
	}
	ps->a[0] = x;
	ps->size++;*/
	SeqListInsert(ps, 0, x);
}


void SeqListPopFront(SeqList* ps)
{
	assert(ps);

	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}


void SeqListPopBack(SeqList* ps)
{
	assert(ps);
	ps->size--;
}


int SeqListFind(SeqList* ps, SLDateType x)
{
	assert(ps);
	
	for (int i = 0; i < ps->size; i++)
	{
		if (ps->a[i] == x)
			return i;
	}
	return -1;
}


void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
	assert(ps);
	assert(0 <= pos && pos <= ps->size);
	CheckCapacity(ps);

	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[pos] = x;
	ps->size++;
}


void SeqListErase(SeqList* ps, int pos)
{
	assert(ps);
	assert(0 <= pos && pos < ps->size);

	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->a[i] = ps->a[i + 1];
	}
	ps->size--;
}